package com.jianbo.proxy.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jianbo.proxy.api.kodApi.Result;
import com.jianbo.proxy.api.kodApi.file.response.FileReadResult;
import com.jianbo.proxy.util.CharsetDetector;
import com.jianbo.proxy.util.FileUtil;

public class IndexService {

    private static Logger logger = LoggerFactory.getLogger(IndexService.class);

    public Result fileGet(String filename) {
        // 文件路径
        FileReadResult read = new FileReadResult();
        read.setFilename(filename);
        read.setBase64(true);

        String type = FileUtil.fileType(filename);
        read.setExt(type);
        Result result = new Result();

        if(filename.equals("memory")) {
            result.setCode(true);
            read.setCharset("utf-8");
            read.setContent(fileContent(""));
            result.setData(read);
            return result;
        }

        File file = new File(filename);
        
        if(file.exists()) {
            result.setCode(true);
            
            read.setCharset("utf-8"); // 固定utf-8编码
            read.setName(file.getName());
            
            try {
                byte[] bytes = FileUtil.readBytes(new FileInputStream(file));
                Charset charset = CharsetDetector.detect(bytes);
                // Charset charset = Charset.forName("utf-8");
                read.setCharset(charset.displayName().toUpperCase());
                String content = Base64.getEncoder().encodeToString(bytes);
                read.setContent(content);

            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                result.setCode(false);
            }

        } else {
            result.setCode(false);
        }

        result.setData(read);
        return result;
    }

    private String fileContent(String string) {
        Charset charset = Charset.forName("utf-8");
        byte[] bytes = string.getBytes(charset);
        String content = Base64.getEncoder().encodeToString(bytes);
        return content;
    }

    public Result fileSave(String path, String filestr) {
        Result result = new Result();
        if("memory".equals(path)) {
            result.setCode(true);
            result.setData("保存成功！");
            return result;
        }
        try {
            filestr = URLDecoder.decode(filestr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            result.setCode(false);
            result.setData("保存失败！");
            return result;    
        }
        byte[] bytes = Base64.getDecoder().decode(filestr);
        // cn.hutool.core.io.FileUtil.writeBytes(bytes, path);
        FileUtil.saveFile(path, bytes);
        result.setCode(true);
        result.setData("保存成功！");
        return result;
    }
}
